package com.example;

import com.alibaba.fastjson.JSONObject;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import javax.persistence.Query;
import java.util.List;

public class ExampleMain {
    public static void main(String[] args) {
        EntityManagerFactory emf = Persistence.createEntityManagerFactory("my-persistence-unit");
        persistEntities(emf);
        loadEntities(emf);
        emf.close();

    }
    private static void persistEntities(EntityManagerFactory emf){
        Employee employee = new Employee("Jackie","Account");
        System.err.println("--- persisting entity ---");
        System.err.println(JSONObject.toJSONString(employee,false));
        EntityManager em = emf.createEntityManager();
        em.getTransaction().begin();
        em.persist(employee);
        employee.setDept("Admin");
        em.getTransaction().commit();
        em.close();
        employee.setDept("IT");
    }
    private static void loadEntities(EntityManagerFactory emf){
        EntityManager em = emf.createEntityManager();
        Query query = em.createQuery("SELECT e from Employee e");
        List<Employee> employees = query.getResultList();
        for (Employee employee : employees) {
            System.err.println(JSONObject.toJSONString(employee,false));
        }
    }
}
